package com.zhangtao.demo.common.util;

import java.io.IOException;

import org.json.JSONObject;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;

public class BaiduSpeechApi {

	// 设置APPID/AK/SK
	public static final String APP_ID = "14603310";
	public static final String API_KEY = "xjqmpLjQhPdOlESGCjzeQuCx";
	public static final String SECRET_KEY = "TOVjd4c0dXV0Be5KnG4UNuVMF67mjnfg";
	private AipSpeech client = null;
	public static final String originPath = "D://download/aaa.wav";
	public static final String pcmPath = "D://download/aaa.pcm";

	public BaiduSpeechApi(String appId, String apiKey, String secretKey) {
		// 初始化一个AipSpeech
		client = new AipSpeech(appId, apiKey, secretKey);

		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);

		// 可选：设置代理服务器地址, http和socket二选一，或者均不设置
		// client.setHttpProxy("proxy_host", this.proxy_port); // 设置http代理
		// client.setSocketProxy("proxy_host", this.proxy_port); // 设置socket代理

		// 调用接口
//		JSONObject res = client.asr(pcmPath, "pcm", 16000, null);
//		System.out.println(res.toString(2));
	}
	public JSONObject asr(byte[] data,String type) {
		JSONObject res = client.asr(data, type, 16000, null);
		System.out.println(res.toString(2));
		return res;
	}

	public void textTransfertoZHVoiceFile(String text, String path) {
		this.textTransfertoVoiceWithLang(text, path, "zh");
	}
	public void textTransfertoVoiceWithLang(String text, String path, String language) {
		System.out.println("use baidu sdk perform text transfer to video action ........................");
		TtsResponse res = client.synthesis(text, language, 1, null);
		byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        if (data != null) {
            try {
                Util.writeBytesToFileSystem(data, path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (res1 != null) {
            System.out.println(res1.toString(2));
        }
	}
}
